package com.security.brows.ui

import android.content.Context
import android.text.format.Formatter
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import coil.compose.AsyncImage
import com.hub.videobrowsdownload.BrowsApplication
import com.hub.videobrowsdownload.BrowsVideoPrepare
import com.hub.videobrowsdownload.R
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable

@Composable
fun ComposeVpProgress(
    downloadingSize: State<Int?>,
    colorsScheme: SecurityBrowsColorsScheme,
    drawableScheme: SecurityBrowsDrawable,
    stateDownloading: LazyListState,
    displayItemTitle: MutableState<Int>
) {
    val context = LocalContext.current
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        if ((downloadingSize.value ?: 0) <= 0) {
            Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                Image(
                    painter = painterResource(id = drawableScheme.no_pending),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(horizontal = 80.dp)
                        .fillMaxWidth(),
                    contentScale = ContentScale.FillWidth
                )

                Spacer(modifier = Modifier.height(13.dp))

                Image(
                    painter = painterResource(id = drawableScheme.how_to_download),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(top = 64.dp, start = 60.dp, end = 60.dp)
                        .fillMaxWidth()
                        .clickable(interactionSource = remember {
                            MutableInteractionSource()
                        }, indication = rememberRipple()) {
                            SecurityBrowsGuideActivity.start(context)
                        },
                    contentScale = ContentScale.FillWidth
                )

            }
        } else {
            val videoList = remember {
                mutableStateListOf<BrowsVideoPrepare>()
            }
            LaunchedEffect(key1 = downloadingSize.value) {
                videoList.clear()
                val elements = BrowsApplication.browsMyViewModel.downloadingTaskMap.values
//                val sortList = elements.sortedWith { o1, o2 ->
//                    val o1State = o1.downloadWrapper.value?.task
//                    val o2State = o1.downloadWrapper.value?.task
//                    if (o1?.downloadWrapper?.value != null && o2?.downloadWrapper?.value != null) {
//                        if (o1State?.isStarted() == true && o2State?.isStarted() == true) {
//                            try {
//                                if ((o1.videoLength.value ?: 0L) > (o2.videoLength.value ?: 0L)) {
//                                    99
//                                } else if ((o1.videoLength.value ?: 0L) < (o2.videoLength.value
//                                        ?: 0L)
//                                ) {
//                                    101
//                                } else {
//                                    100
//                                }
//                            } catch (e: Exception) {
//                                100
//                            }
//                        } else if (o1State?.isStarted() == true) {
//                            99
//                        } else if (o2State?.isStarted() == true) {
//                            101
//                        } else {
//                            100
//                        }
//
//                    } else if (o1State?.isStarted() == true) {
//                        99
//                    } else if (o2State?.isStarted() == true) {
//                        101
//                    } else {
//                        try {
//                            if ((o1.videoLength.value ?: 0L) > (o2.videoLength.value ?: 0L)) {
//                                -1
//                            } else if ((o1.videoLength.value ?: 0L) < (o2.videoLength.value
//                                    ?: 0L)
//                            ) {
//                                1
//                            } else {
//                                0
//                            }
//                        } catch (e: Exception) {
//                            0
//                        }
//                    }
//                }
                videoList.addAll(elements)
            }
            LazyColumn(Modifier.fillMaxSize(), state = stateDownloading, verticalArrangement = Arrangement.spacedBy(16.dp)) {

                items(videoList, key = { it.getVideoId() }) { videoPrepare ->
                    LazyItems(videoPrepare, videoList, context, drawableScheme, colorsScheme, displayItemTitle)
                }

                item { Spacer(modifier = Modifier.height(16.dp)) }

            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun LazyItemScope.LazyItems(
    videoPrepare: BrowsVideoPrepare,
    videoList: SnapshotStateList<BrowsVideoPrepare>,
    context: Context,
    drawableScheme: SecurityBrowsDrawable,
    colorsScheme: SecurityBrowsColorsScheme,
    displayItemTitle: MutableState<Int>
) {
    val downloadWrapper = videoPrepare.downloadWrapper.observeAsState()
    val downloadSpeedLength = videoPrepare.downloadSpeedLength.observeAsState(0L)
    val showPopupMenu = remember {
        mutableStateOf(false)
    }

    Row(
        Modifier
            .animateItemPlacement()
            .fillMaxWidth()
            .height(88.dp)
            .background(colorsScheme.browsBg),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Spacer(modifier = Modifier.width(8.dp))
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(12.dp))
                .padding(8.dp)
                .fillMaxHeight()
                .aspectRatio(110f / 72f, true)
                .clickable {
                    try {
                        if (downloadWrapper.value?.task?.isStarted() == true) {
                            downloadWrapper.value?.task?.stop()
                        } else {
                            val isActive = downloadWrapper.value?.task?.start()
                            if (isActive != true && downloadWrapper.value?.task?.isFailed() == true) {
                                BrowsApplication.browsMyViewModel.startDownload(
                                    context,
                                    videoPrepare
                                )
                            } else {

                            }
                        }
                    } catch (e: Exception) {

                        e.printStackTrace()
                    }
                }
        ) {

            AsyncImage(
                model = videoPrepare.getThumbFile(context),
                contentDescription = null,
                modifier = Modifier
                    .clip(RoundedCornerShape(12.dp))
                    .fillMaxSize(),
                contentScale = ContentScale.Crop,
            )
            Column(
                modifier = Modifier.align(Alignment.Center),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                if (downloadWrapper.value?.state is com.forest.download.State.Succeed) {

                } else if (downloadWrapper.value?.state is com.forest.download.State.Downloading) {
                    Image(
                        painter = painterResource(id = drawableScheme.pause_icon),
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        contentScale = ContentScale.FillBounds
                    )
                } else {
                    Image(
                        painter = painterResource(id = drawableScheme.download_icon),
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
            }
        }

        Spacer(modifier = Modifier.width(10.dp))
        Column(
            Modifier
                .weight(1f)
                .fillMaxHeight()
                .clickable {
                    if (videoPrepare.webUrl.isNotEmpty()) {
                        SecurityBrowsTabWebActivity.start(
                            context,
                            videoPrepare.webUrl
                        )
                    }
                }, verticalArrangement = Arrangement.Center
        ) {
            Text(
                text =  if (displayItemTitle.value == 1) videoPrepare.title.toString() else videoPrepare.getFileName(),
                color = colorsScheme.progressDownloadTitle,
                fontSize = 16.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Spacer(modifier = Modifier.height(5.dp))
            var text = " "
            if (videoPrepare.videoWidth.value != 0 && videoPrepare.videoHeight.value != 0) {
                text = "${videoPrepare.videoWidth.value}X${videoPrepare.videoHeight.value}"
            }
            Text(
                text = text,
                color = colorsScheme.progressDownloadResolution,
                fontSize = 14.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Spacer(modifier = Modifier.height(2.dp))
            Box(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = videoPrepare.getStateMessage(downloadWrapper.value),
                    color = if (downloadWrapper.value?.state is com.forest.download.State.Downloading || downloadWrapper.value?.state is com.forest.download.State.Succeed) colorsScheme.progressDownloadState else colorsScheme.progressDownloadStateError,
                    fontSize = 12.sp,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = Formatter.formatFileSize(context, downloadSpeedLength.value!!)
                        .replace(" ", "").uppercase() + "/S",
                    color = colorsScheme.progressDownloadResolution,
                    fontSize = 12.sp,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.align(Alignment.CenterEnd)
                )
            }
            Spacer(modifier = Modifier.height(2.dp))
            LinearProgressIndicator(
                downloadWrapper.value?.state?.progress?.progress()
                    ?: 0f,
                color = colorsScheme.progressPbColor,
                trackColor = colorsScheme.progressPbtrackColor,
                strokeCap = StrokeCap.Round,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(4.dp)
            )
        }
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .width(36.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    showPopupMenu.value = true
                }
        ) {
            Image(
                painter = painterResource(id = drawableScheme.video_menu),
                contentDescription = null,
                modifier = Modifier
                    .align(
                        Alignment.Center
                    )
                    .size(20.dp)
            )

            if (showPopupMenu.value && downloadWrapper.value?.task?.isSucceed() != true) {
                PopCompose(showPopupMenu, drawableScheme, colorsScheme, videoPrepare, videoList)
            }
        }
    }
}

@Composable
private fun PopCompose(
    showPopupMenu: MutableState<Boolean>,
    drawableScheme: SecurityBrowsDrawable,
    colorsScheme: SecurityBrowsColorsScheme,
    videoPrepare: BrowsVideoPrepare,
    videoList: SnapshotStateList<BrowsVideoPrepare>,
) {
    val context = LocalContext.current
    BackHandler(showPopupMenu.value) {
        showPopupMenu.value = false
    }

    val offsetX = with(LocalDensity.current) { 8.dp.toPx() }
    val offsetY = with(LocalDensity.current) { 8.dp.toPx() }
    Popup(offset = IntOffset(-offsetX.toInt(), offsetY.toInt()),
        alignment = Alignment.TopEnd,
        onDismissRequest = { showPopupMenu.value = false }) {
        Column(
            Modifier
                .width(56.dp)
                .border(1.dp, color = colorsScheme.homeTitleSpace, RoundedCornerShape(6.dp))
                .background(color = colorsScheme.browsBg, RoundedCornerShape(6.dp))
        ) {
            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (videoPrepare.webUrl.isNotEmpty()) {
                        SecurityBrowsTabWebActivity.start(
                            context,
                            videoPrepare.webUrl
                        )
                    }
                }) {

                Image(
                    painter = painterResource(id = drawableScheme.video_web),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }
            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    try {
                        videoList.remove(videoPrepare)
                    } catch (e: Exception) {

                    }
                    BrowsApplication.browsMyViewModel.rmDownloading(
                        context,
                        videoPrepare
                    )
                }) {

                Image(
                    painter = painterResource(id = drawableScheme.video_delete),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }
            Box(modifier = Modifier
                .size(56.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (videoPrepare.webUrl.isNotEmpty()) {
                        SecurityBrowsTabWebActivity.startSafari(
                            context,
                            videoPrepare.webUrl
                        )
                    }
                }) {

                Image(
                    painter = painterResource(id = R.drawable.brows_safari_icon),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(20.dp),
                    contentScale = ContentScale.FillBounds
                )
            }
        }
    }
}